package com.yanqu.road.server.timer.player;

import com.yanqu.road.entity.enums.ePlayerAttrType;
import com.yanqu.road.entity.event.EventTriggerArgs;
import com.yanqu.road.entity.player.PlayerState;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.AttributeModule;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.PlayerInfoChangeNotifyMgr;
import com.yanqu.road.server.manger.player.task.PlayInfoChangeType;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.executor.GeneralTask;

import java.util.Map;

/**
 * 统一玩家每日在线时长统计(按分钟统计)
 * 有误差（1分钟内）
 */
public class PlayerOnlineCalTask extends GeneralTask {

    /**
     * 上次计算时间
     */
    public static long lastCalOnlineTime = System.currentTimeMillis();

    @Override
    public void doRun() {

        long zeroTimeStamp = DateHelper.getTodayZeroTimeStamp();

        Map<Long, GamePlayer> copyPlayerMap = GamePlayerMgr.getCopyPlayerMap();
        for (Map.Entry<Long, GamePlayer> entry : copyPlayerMap.entrySet()) {
            GamePlayer player = entry.getValue();
            AttributeModule attributeModule = player.getModule(AttributeModule.class);
            //每日重置
            long resetTime = attributeModule.getAttribute(ePlayerAttrType.DailyOnlineTimeRestTime);
            if(resetTime == 0){
                attributeModule.setAttribute(ePlayerAttrType.DailyOnlineTimeRestTime, zeroTimeStamp);
            }else if(zeroTimeStamp != resetTime){
                attributeModule.setAttribute(ePlayerAttrType.DailyOnlineTimeRestTime, zeroTimeStamp);
                attributeModule.setAttribute(ePlayerAttrType.DailyOnlineTime, 0);
            }
        }

        long nowTime = System.currentTimeMillis();
        if(nowTime - lastCalOnlineTime >= DateHelper.MINUTE_MILLIONS){
            long add = (nowTime - lastCalOnlineTime) / DateHelper.MINUTE_MILLIONS;
            for (Map.Entry<Long, GamePlayer> entry : copyPlayerMap.entrySet()) {
                GamePlayer player = entry.getValue();
                if (player.getState() == PlayerState.ONLINE) {
                    //加在线时长
                    AttributeModule attributeModule = player.getModule(AttributeModule.class);
                    attributeModule.setAttribute(ePlayerAttrType.DailyOnlineTime, attributeModule.getAttribute(ePlayerAttrType.DailyOnlineTime) + add);
                    //通知变更
                    PlayerInfoChangeNotifyMgr.notifyReload(PlayInfoChangeType.DailyOnlineTime.getType(), player.getUserId(), new EventTriggerArgs(attributeModule.getAttribute(ePlayerAttrType.DailyOnlineTime)));
                }
            }
            lastCalOnlineTime += add * DateHelper.MINUTE_MILLIONS;
        }
    }
}
